package com.simdo.g768.Util;

import java.lang.reflect.Type;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.reflect.TypeToken;
import com.simdo.g768.Bean.MyUeidBean;
import com.simdo.g768.Bean.object.ControlConfig;
import com.simdo.g768.Bean.object.TraceConfig;


public class GsonUtil {

    /**
     * 对象转换为json
     */
    public static String createJsonString(Object value) {
        Gson gson = new Gson();
        return gson.toJson(value);
    }

    public static JsonObject getJsonObject(Object value){
        Gson gson = new Gson();
        return JsonParser.parseString(gson.toJson(value)).getAsJsonObject();
    }

    /**
     * json 转换为对象
     */
    public static <T> T getPerson(String jsonString, Class<T> clazz) {
        T t = null;
        try {
            Gson gson = new Gson();
            t = gson.fromJson(jsonString, clazz);
        } catch (Exception e) {
            AppLog.E(MessageFormat.format("JSON转换成对象失败!!{0}{1}", jsonString, e));
        }
        return t;
    }

    /**
     * json转换为List<Object>
     */
    public static <T> List<T> getPersons(String jsonString, Class<T[]> clazz) {
        Gson gson = new Gson();
        T[] array = gson.fromJson(jsonString, clazz);
        return Arrays.asList(array);
    }

    /**
     * 将Map转化为Json
     */
    public static <T> String mapToJson(HashMap<Integer, T> map) {
        Gson gson = new Gson();
        return gson.toJson(map);
    }

    public static HashMap<Integer, TraceConfig> jsonToMap(String json){
        //AppLog.D("jsonToMap json = " + json);
        Gson gson = new Gson();
        Type type = new TypeToken<Map<Integer, TraceConfig>>(){}.getType();
        return gson.fromJson(json, type);
    }

    public static String strMapToJson(HashMap<String, String> map) {
        Gson gson = new Gson();
        return gson.toJson(map);
    }

    public static HashMap<String, String> jsonToStrMap(String json){
        //AppLog.D("jsonToStrMap json = " + json);
        Gson gson = new Gson();
        Type type = new TypeToken<HashMap<String, String>>(){}.getType();
        return gson.fromJson(json, type);
    }

    public static String listMapToJson(HashMap<Integer, List<String>> map) {
        Gson gson = new Gson();
        return gson.toJson(map);
    }

    public static HashMap<Integer, List<String>> jsonToListMap(String json){
        //AppLog.D("jsonToListMap json = " + json);
        Gson gson = new Gson();
        Type type = new TypeToken<HashMap<Integer, List<String>>>(){}.getType();
        return gson.fromJson(json, type);
    }
}

